package com.zwq.exception;

import com.zwq.util.ResponseResult;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.http.HttpStatus;
import org.springframework.web.context.request.WebRequest;

@RestControllerAdvice
public class GlobalExceptionHandler {

    private static final Logger logger = LoggerFactory.getLogger(GlobalExceptionHandler.class);

    @ExceptionHandler(BusinessException.class)
    @ResponseBody
    public ResponseResult<?> handleBusinessException(Exception e,
                                                     HttpServletRequest request,
                                                     HttpServletResponse response) {

        logger.error("an business exception occurred: \n\t{}", e.toString());

        response.setStatus(HttpStatus.BAD_REQUEST.value());
        return ResponseResult.error(HttpStatus.BAD_REQUEST.value(), e.getMessage());
    }

    @ExceptionHandler(Exception.class)
    @ResponseBody
    public ResponseResult<?> handleException(Exception e,
                                              HttpServletRequest request,
                                              HttpServletResponse response) {

        logger.error("an system exception occurred: \n\t{}", e.toString());

        response.setStatus(HttpStatus.INTERNAL_SERVER_ERROR.value());
        return ResponseResult.error(HttpStatus.INTERNAL_SERVER_ERROR.value(), e.getMessage());
    }
}